package cn.seapon.talkerserver.common;

import java.io.Serializable;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;


/** 
 * @author 作者 E-mail: 
 * @version 创建时间：2014年12月28日 下午8:51:50 
 * 类说明 
 */
public class MessageReceiver implements Serializable{

	private ArrayList<String> receivers = new ArrayList<String>();
	private int count = 0;
	
	
	public JSONArray getJSONArray() {
		JSONArray array = new JSONArray();
		String[] receivers =  getAllReceiver() ;
		for (int i = 0; i < receivers.length; i++) {
			array.put(receivers[i]);
		}
		return array;
	}
	
	public static MessageReceiver getObjectFromJson(JSONArray array){
		MessageReceiver receiver = new MessageReceiver();
		for (int i = 0; i < array.length(); i++) {
			try {
				receiver.addReceiver(array.getString(i));
			} catch (JSONException e) {
				e.printStackTrace();
				return null;
			}
		}
		return receiver;
	}
	
	
	public MessageReceiver(String receiver) {
		receivers.add(count++,receiver);
	}

	public MessageReceiver() {
	}

	/**
	 * 加入接受者的ＩＤ
	 * @param receiverId
	 */
	public void addReceiver(String receiverId) {
		receivers.add(count++,receiverId);
	}
	
	/**
	 * 一对一聊天室返回唯一的接受者
	 * @return 有多人或者无人时返回null
	 */
	public String getTheReceiver() {
		if (receivers.size() == 1) {
			return receivers.get(0);
		}
		return null;
	}
	

	public String[] getAllReceiver() {
		/**
		 * 指定数组类型和长度，如果指定长度为0或小于集合的size时，会内部新建一个数组
		 */
		return receivers.toArray(new String[count]);
	}
	
	public int length() {
		return count;
	}
	
}
